# 用Python实现一个函数 2个Po文件的合并，例如a.po,b.po,b.po内的所有项覆盖到a.po中，更新a.po文件


import polib
import json

def merge_po_files(file_a, file_b):
    po_a = polib.pofile(file_a)
    po_b = polib.pofile(file_b)

    for entry_b in po_b:
        for entry_a in po_a:
            if entry_a.msgid == entry_b.msgid:
                entry_a.msgstr = entry_b.msgstr
                break
        else:
            po_a.append(entry_b)

    po_a.save(file_a)


# /comments/merge_po_files('a.po', 'b.po')
def merge_json2po(po_file_path, json_file_path):
    # Load the .po file
    po = polib.pofile(po_file_path)
    
    # Load the JSON content
    with open(json_file_path, 'r', encoding='utf-8') as json_file:
        translations = json.load(json_file)

    # Merge the JSON translations into the .po file
    for entry in po:
        if entry.msgid in translations:
            entry.msgstr = translations[entry.msgid]

    # Save the merged .po file
    po.save(po_file_path)

# Usage example
# merge_po('path_to_po_file.po', 'path_to_json_file.json')


#a_file = r"C:\Users\jan\Documents\Project\CproScada\cpro_scada\dist\translations\CPro_English.po"
# b_file = r"C:\Users\jan\Documents\WeChat Files\siegjan6\FileStorage\File\2023-06\Cpro_English.po"

a_file = r"C:\Users\jan\Documents\Project\CproScada\cpro_scada\dist\translations\CPro_Russian.po"
b_file = r"C:\Users\jan\Downloads\Merged_CPro_Russian.json"

# 调用函数
merge_json2po(a_file,b_file)
